import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useDarkModeStore = defineStore('darkMode', () => {
  const isDark = ref( false)

  const toggleDarkMode = () => {
    isDark.value = !isDark.value
    updateDarkModeClass()
  }

  const updateDarkModeClass = () => {
    const html = document.documentElement
    if (isDark.value) {
      html.classList.add('dark')
      html.style.colorScheme = 'dark'
    } else {
      html.classList.remove('dark')
      html.style.colorScheme = 'light'
    }
  }

  // 初始化
  updateDarkModeClass()

  // 监听变化
  watch(isDark, updateDarkModeClass)

  return { isDark, toggleDarkMode }
})
